package com.qihang.librarymanage.jframe.user;

import com.qihang.librarymanage.pojo.User;
import com.qihang.librarymanage.jframe.user.UserPage;
import com.qihang.librarymanage.jframe.user.BookSearch;
import com.qihang.librarymanage.utils.Theme;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class BookInfo extends JFrame {
    private JPanel mainPanel;
    private JPanel booksPanel;
    private JScrollPane scrollPane;
    private User user;

    private final ArrayList<BookDisplay> allBooks = new ArrayList<>();
    private List<BookDisplay> filteredAndSortedBooks = new ArrayList<>();

    private int currentPage = 1;
    private int itemsPerPage = 8;

    private JComboBox<String> sortComboBox;
    private JTextField minPriceField, maxPriceField;
    private JTextField startYearField, endYearField;
    private JComboBox<String> publisherComboBox;
    private JTree categoryTree;
    private DefaultMutableTreeNode selectedCategoryNode;


    private JLabel pageInfoLabel;
    private JButton prevButton, nextButton;
    private JComboBox<Integer> itemsPerPageComboBox;


    // 模拟的书籍信息，真实项目中应该从数据库获取
    private class BookDisplay {
        private final int id;
        private final String title;
        private final String author;
        private final double price;
        private final String type;
        private final String description;
        private ImageIcon cover;

        private final int publicationYear;
        private final String publisher;
        private final double rating;
        private final int borrowCount;


        public BookDisplay(int id, String title, String author, double price, String type, String description, String imagePath, int publicationYear, String publisher, double rating, int borrowCount) {
            this.id = id;
            this.title = title;
            this.author = author;
            this.price = price;
            this.type = type; // This is the category
            this.description = description;
            this.publicationYear = publicationYear;
            this.publisher = publisher;
            this.rating = rating;
            this.borrowCount = borrowCount;

            // 加载图书封面图片，如果找不到则创建一个空白图片
            try {
                this.cover = new ImageIcon(getClass().getResource("/images/" + imagePath));
                // 调整图片大小
                if (this.cover.getIconWidth() > 0) {
                    Image image = cover.getImage().getScaledInstance(150, 200, Image.SCALE_SMOOTH);
                    this.cover = new ImageIcon(image);
                } else {
                    createDefaultCover();
                }
            } catch (Exception e) {
                createDefaultCover();
            }
        }

        private void createDefaultCover() {
            // 创建一个120x160的带书名的默认封面
            BufferedImage bufferedImage = new BufferedImage(120, 160, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();

            // 设置背景色
            g2d.setColor(new Color(240, 240, 240));
            g2d.fillRect(0, 0, 120, 160);

            // 绘制边框
            g2d.setColor(Color.GRAY);
            g2d.drawRect(0, 0, 119, 159);

            // 绘制书名
            g2d.setColor(Color.BLACK);
            g2d.setFont(new Font("微软雅黑", Font.BOLD, 14));
            FontMetrics metrics = g2d.getFontMetrics();
            int titleWidth = metrics.stringWidth(title);
            int x = (120 - titleWidth) / 2;
            g2d.drawString(title, Math.max(x, 5), 80);

            g2d.dispose();
            this.cover = new ImageIcon(bufferedImage);
        }

        // Getters for sorting and filtering
        public double getPrice() { return price; }
        public int getPublicationYear() { return publicationYear; }
        public double getRating() { return rating; }
        public int getBorrowCount() { return borrowCount; }
        public String getPublisher() { return publisher; }
        public String getType() { return type; }
        public String getDescription() { return description; }
    }

    public BookInfo() {
        this(null);
    }

    public BookInfo(User user) {
        // 应用Theme 1主题
        new Theme(1);
        
        this.user = user;

        // 设置窗口属性
        setTitle("图书浏览");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1200, 800);
        setLocationRelativeTo(null);
        getContentPane().setBackground(new Color(250, 250, 255));

        // 创建主面板
        mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(new Color(250, 250, 255));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        
        // 创建顶部面板，用于显示用户登录信息
        JPanel topPanel = createTopPanel();
        mainPanel.add(topPanel, BorderLayout.NORTH);

        // 创建左侧的筛选和排序面板
        JPanel filterPanel = createFilterPanel();
        mainPanel.add(filterPanel, BorderLayout.WEST);

        // 创建书籍展示面板（使用网格布局）
        booksPanel = new JPanel();
        booksPanel.setLayout(new GridLayout(0, 4, 20, 20));
        booksPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        booksPanel.setBackground(new Color(250, 250, 255));

        // 创建滚动面板
        scrollPane = new JScrollPane(booksPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16); // 设置滚动速度
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.setBackground(new Color(250, 250, 255));
        scrollPane.getViewport().setBackground(new Color(250, 250, 255));
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建底部的分页面板
        JPanel paginationPanel = createPaginationPanel();
        mainPanel.add(paginationPanel, BorderLayout.SOUTH);

        // 加载书籍数据
        loadBooks();
        updateBookDisplay();

        setContentPane(mainPanel);
        setVisible(true);
    }

    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
        panel.setBackground(new Color(245, 245, 250));
        
        // 创建左侧标题
        JLabel titleLabel = new JLabel("图书浏览");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(new Color(50, 50, 80));
        panel.add(titleLabel, BorderLayout.WEST);
        
        // 创建显示用户信息的标签
        JLabel userInfoLabel = new JLabel();
        if (user != null) {
            userInfoLabel.setText("当前用户：" + user.getUserName());
        } else {
            userInfoLabel.setText("未登录");
        }
        userInfoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        userInfoLabel.setForeground(new Color(80, 80, 120));
        
        // 将标签添加到面板的右侧
        panel.add(userInfoLabel, BorderLayout.EAST);
        
        return panel;
    }

    private JPanel createFilterPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(10, 15, 10, 15),
                BorderFactory.createCompoundBorder(
                    new LineBorder(new Color(230, 230, 240), 1, true),
                    BorderFactory.createEmptyBorder(15, 15, 15, 15)
                )
        ));
        panel.setBackground(new Color(250, 250, 255));
        panel.setPreferredSize(new Dimension(220, 0));

        // 用户中心按钮
        JButton userCenterButton = new JButton("用户中心");
        userCenterButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        userCenterButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        userCenterButton.setBackground(new Color(100, 120, 200));
        userCenterButton.setForeground(Color.WHITE);
        userCenterButton.setFocusPainted(false);
        userCenterButton.setBorderPainted(false);
        userCenterButton.setPreferredSize(new Dimension(180, 40));
        userCenterButton.setMaximumSize(new Dimension(180, 40));
        userCenterButton.setMinimumSize(new Dimension(180, 40));
        userCenterButton.addActionListener(e -> {
            // 跳转到用户中心页面
            dispose();
            // 添加用户对象为空的检查
            if (user != null) {
                new UserCenterPage(user);
            } else {
                JOptionPane.showMessageDialog(null, "请先登录后再访问用户中心", "提示", JOptionPane.WARNING_MESSAGE);
                // 如果用户未登录，跳转到图书搜索页面
                new BookSearch();
            }
        });
        panel.add(userCenterButton);
        panel.add(Box.createVerticalStrut(15));

        // 搜索书籍按钮
        JButton searchBookButton = new JButton("搜索书籍");
        searchBookButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        searchBookButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        searchBookButton.setBackground(new Color(100, 180, 160));
        searchBookButton.setForeground(Color.WHITE);
        searchBookButton.setFocusPainted(false);
        searchBookButton.setBorderPainted(false);
        searchBookButton.setPreferredSize(new Dimension(180, 40));
        searchBookButton.setMaximumSize(new Dimension(180, 40));
        searchBookButton.setMinimumSize(new Dimension(180, 40));
        searchBookButton.addActionListener(e -> {
            dispose(); // 关闭当前窗口
            SwingUtilities.invokeLater(() -> {
                BookSearch bookSearch = new BookSearch();
                bookSearch.setVisible(true);
            });
        });
        panel.add(searchBookButton);
        panel.add(Box.createVerticalStrut(20));

        // 只保留图书分类
        JPanel categoryPanel = new JPanel(new BorderLayout());
        categoryPanel.setBorder(BorderFactory.createTitledBorder(
            new LineBorder(new Color(200, 200, 220), 1, true),
            "图书分类",
            TitledBorder.LEFT,
            TitledBorder.TOP,
            new Font("微软雅黑", Font.BOLD, 14),
            new Color(80, 80, 120)
        ));
        categoryPanel.setBackground(new Color(250, 250, 255));
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("所有分类");
        DefaultMutableTreeNode classics = new DefaultMutableTreeNode("经典著作");
        classics.add(new DefaultMutableTreeNode("中国古典"));
        classics.add(new DefaultMutableTreeNode("外国经典"));
        DefaultMutableTreeNode fiction = new DefaultMutableTreeNode("小说");
        fiction.add(new DefaultMutableTreeNode("科幻"));
        fiction.add(new DefaultMutableTreeNode("悬疑"));
        root.add(classics);
        root.add(fiction);
        categoryTree = new JTree(root);
        categoryTree.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        categoryTree.setBackground(new Color(250, 250, 255));
        categoryTree.addTreeSelectionListener(e -> {
            selectedCategoryNode = (DefaultMutableTreeNode) categoryTree.getLastSelectedPathComponent();
        });
        JScrollPane treeScrollPane = new JScrollPane(categoryTree);
        treeScrollPane.setPreferredSize(new Dimension(180, 150));
        treeScrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        categoryPanel.add(treeScrollPane, BorderLayout.CENTER);

        // 应用筛选按钮
        JButton applyButton = new JButton("筛选");
        applyButton.setPreferredSize(new Dimension(180, 40));
        applyButton.setMaximumSize(new Dimension(180, 40));
        applyButton.setMinimumSize(new Dimension(180, 40));
        applyButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        applyButton.setBackground(new Color(80, 140, 220));
        applyButton.setForeground(Color.WHITE);
        applyButton.setFocusPainted(false);
        applyButton.setBorderPainted(false);
        applyButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        applyButton.addActionListener(e -> {
            currentPage = 1; // 筛选后回到第一页
            updateBookDisplay();
        });

        panel.add(categoryPanel);
        panel.add(Box.createVerticalStrut(20));
        panel.add(applyButton);
        panel.add(Box.createVerticalGlue()); // Pushes button to bottom

        return panel;
    }

    private JPanel createPaginationPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        panel.setBackground(new Color(245, 245, 250));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 0, 10, 0));

        // 固定为8个条目每页
        itemsPerPage = 8;

        prevButton = new JButton("上一页");
        prevButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        prevButton.setBackground(new Color(100, 140, 220));
        prevButton.setForeground(Color.WHITE);
        prevButton.setFocusPainted(false);
        prevButton.setBorderPainted(false);
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                updateBookDisplay();
            }
        });

        pageInfoLabel = new JLabel("第 1 / 1 页");
        pageInfoLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        pageInfoLabel.setForeground(new Color(80, 80, 120));
        pageInfoLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));

        nextButton = new JButton("下一页");
        nextButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        nextButton.setBackground(new Color(100, 140, 220));
        nextButton.setForeground(Color.WHITE);
        nextButton.setFocusPainted(false);
        nextButton.setBorderPainted(false);
        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) filteredAndSortedBooks.size() / itemsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                updateBookDisplay();
            }
        });

        panel.add(prevButton);
        panel.add(pageInfoLabel);
        panel.add(nextButton);

        return panel;
    }


    private void updateBookDisplay() {
        // 只按分类过滤
        List<BookDisplay> filteredBooks = allBooks.stream()
                .filter(this::filterByCategory)
                .collect(Collectors.toList());

        // 2. Sorting
        String sortOption = null;
        this.filteredAndSortedBooks = filteredBooks;

        // 3. Pagination
        int totalItems = filteredAndSortedBooks.size();
        int totalPages = (int) Math.ceil((double) totalItems / itemsPerPage);
        if (totalPages == 0) totalPages = 1;
        if (currentPage > totalPages) {
            currentPage = totalPages;
        }

        int startIndex = (currentPage - 1) * itemsPerPage;
        int endIndex = Math.min(startIndex + itemsPerPage, totalItems);

        List<BookDisplay> booksForCurrentPage = filteredAndSortedBooks.subList(startIndex, endIndex);
        displayBooksOnPanel(booksForCurrentPage);

        // 4. Update UI controls
        pageInfoLabel.setText("第 " + currentPage + " / " + totalPages + " 页");
        prevButton.setEnabled(currentPage > 1);
        nextButton.setEnabled(currentPage < totalPages);
        
        // 更新按钮颜色
        if (prevButton.isEnabled()) {
            prevButton.setBackground(new Color(100, 140, 220));
        } else {
            prevButton.setBackground(new Color(180, 180, 200));
        }
        
        if (nextButton.isEnabled()) {
            nextButton.setBackground(new Color(100, 140, 220));
        } else {
            nextButton.setBackground(new Color(180, 180, 200));
        }
    }

    private boolean filterByPrice(BookDisplay book) {
        String minText = minPriceField.getText();
        String maxText = maxPriceField.getText();
        try {
            double minPrice = minText.isEmpty() ? 0 : Double.parseDouble(minText);
            double maxPrice = maxText.isEmpty() ? Double.MAX_VALUE : Double.parseDouble(maxText);
            return book.getPrice() >= minPrice && book.getPrice() <= maxPrice;
        } catch (NumberFormatException e) {
            return true; // If input is invalid, don't filter
        }
    }

    private boolean filterByYear(BookDisplay book) {
        String startText = startYearField.getText();
        String endText = endYearField.getText();
        try {
            int startYear = startText.isEmpty() ? 0 : Integer.parseInt(startText);
            int endYear = endText.isEmpty() ? Integer.MAX_VALUE : Integer.parseInt(endText);
            return book.getPublicationYear() >= startYear && book.getPublicationYear() <= endYear;
        } catch (NumberFormatException e) {
            return true;
        }
    }

    private boolean filterByPublisher(BookDisplay book) {
        String selectedPublisher = (String) publisherComboBox.getSelectedItem();
        if (selectedPublisher == null || selectedPublisher.equals("所有")) {
            return true;
        }
        return book.getPublisher().equals(selectedPublisher);
    }

    private boolean filterByCategory(BookDisplay book) {
        if (selectedCategoryNode == null || selectedCategoryNode.isRoot()) {
            return true;
        }
        // This is a simple implementation. A better one would check parent categories.
        // For example, if "经典著作" is selected, both "中国古典" and "外国经典" should be shown.
        if (selectedCategoryNode.isLeaf()) {
            return book.getType().equals(selectedCategoryNode.getUserObject().toString());
        } else { // It's a parent category
            for (int i=0; i<selectedCategoryNode.getChildCount(); i++) {
                if (book.getType().equals(((DefaultMutableTreeNode)selectedCategoryNode.getChildAt(i)).getUserObject().toString())) {
                    return true;
                }
            }
            return false;
        }
    }


    private void loadBooks() {
        // 在实际应用中，这里应该从数据库加载书籍信息
        allBooks.add(new BookDisplay(1, "红楼梦", "曹雪芹", 100.0, "中国古典", "...", "hongloumeng.jpg", 1791, "人民文学出版社", 9.8, 1500));
        allBooks.add(new BookDisplay(2, "西游记", "吴承恩", 106.0, "中国古典", "...", "xiyouji.jpg", 1592, "人民文学出版社", 9.5, 1800));
        allBooks.add(new BookDisplay(3, "三体", "刘慈欣", 68.0, "科幻", "...", "default_book.png", 2008, "重庆出版社", 9.4, 2500));
        allBooks.add(new BookDisplay(4, "水浒传", "施耐庵", 60.0, "中国古典", "...", "shuihuzhuan.jpg", 1500, "人民文学出版社", 9.1, 1200));
        allBooks.add(new BookDisplay(5, "骆驼祥子", "老舍", 32.0, "中国古典", "...", "luotuoxiangzi.jpg", 1937, "人民文学出版社", 8.9, 900));
        allBooks.add(new BookDisplay(6, "李清照词集", "李清照", 89.0, "中国古典", "...", "liqingzhao.jpg", 1100, "江苏出版社", 9.2, 500));
        allBooks.add(new BookDisplay(7, "红与黑", "司汤达", 59.0, "外国经典", "...", "hongyuhei.jpg", 1830, "江苏出版社", 8.8, 750));
        allBooks.add(new BookDisplay(8, "堂吉诃德", "塞万提斯", 67.0, "外国经典", "...", "tangjihuode.jpg", 1605, "江苏出版社", 8.7, 600));
        allBooks.add(new BookDisplay(9, "代码大全", "史蒂夫·迈克康奈尔", 128.0, "计算机", "...", "default_book.png", 2004, "机械工业出版社", 9.3, 1100));
        allBooks.add(new BookDisplay(10, "福尔摩斯探案全集", "柯南·道尔", 99.0, "悬疑", "...", "default_book.png", 1887, "江苏出版社", 9.0, 1300));
        allBooks.add(new BookDisplay(11, "百年孤独", "加西亚·马尔克斯", 45.0, "外国经典", "...", "default_book.png", 1967, "南海出版公司", 9.5, 2200));
        allBooks.add(new BookDisplay(12, "活着", "余华", 28.0, "小说", "...", "default_book.png", 1993, "作家出版社", 9.4, 1900));
        allBooks.add(new BookDisplay(13, "Effective Java", "Joshua Bloch", 98.0, "计算机", "...", "default_book.png", 2017, "机械工业出版社", 9.7, 1400));
        allBooks.add(new BookDisplay(14, "解忧杂货店", "东野圭吾", 39.5, "小说", "...", "default_book.png", 2012, "南海出版公司", 8.5, 2800));
        allBooks.add(new BookDisplay(15, "围城", "钱钟书", 36.0, "小说", "...", "default_book.png", 1947, "人民文学出版社", 9.2, 1600));
        allBooks.add(new BookDisplay(16, "漫长的告别", "雷蒙德·钱德勒", 55.0, "悬疑", "...", "default_book.png", 1953, "南海出版公司", 8.6, 850));
    }


    private void displayBooksOnPanel(List<BookDisplay> books) {
        booksPanel.removeAll();

        for (BookDisplay book : books) {
            JPanel bookPanel = createBookPanel(book);
            booksPanel.add(bookPanel);
        }

        booksPanel.revalidate();
        booksPanel.repaint();
    }

    private JPanel createBookPanel(BookDisplay book) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        // 移除边框，只保留内边距
        panel.setBorder(BorderFactory.createEmptyBorder(8, 10, 8, 10));
        panel.setBackground(Color.WHITE);
        panel.setAlignmentX(Component.CENTER_ALIGNMENT);

        // 添加鼠标悬停效果
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                // 鼠标悬停时不显示边框，只改变背景色
                panel.setBackground(new Color(250, 250, 255));
                panel.setCursor(new Cursor(Cursor.HAND_CURSOR));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                // 恢复原来的背景色
                panel.setBackground(Color.WHITE);
                panel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                dispose(); // 关闭当前窗口
                new BookDetails(book.title, book.author, book.price, book.getDescription(), book.cover);
            }
        });

        // 封面图片 - 调整大小
        Image scaledImage = book.cover.getImage().getScaledInstance(120, 160, Image.SCALE_SMOOTH);
        JLabel coverLabel = new JLabel(new ImageIcon(scaledImage));
        coverLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(coverLabel);

        panel.add(Box.createRigidArea(new Dimension(0, 5)));

        // 书名 - 减小字体
        JLabel titleLabel = createWrappedLabel("书名: " + book.title, new Font("微软雅黑", Font.BOLD, 13));
        panel.add(titleLabel);

        panel.add(Box.createRigidArea(new Dimension(0, 2)));

        // 作者 - 减小字体
        JLabel authorLabel = createWrappedLabel("作者: " + book.author, new Font("微软雅黑", Font.PLAIN, 11));
        panel.add(authorLabel);

        panel.add(Box.createRigidArea(new Dimension(0, 2)));

        // 价格 - 减小字体
        JLabel priceLabel = createWrappedLabel("价格: " + book.price + "元", new Font("微软雅黑", Font.PLAIN, 11));
        panel.add(priceLabel);
        
        panel.add(Box.createRigidArea(new Dimension(0, 2)));
        
        // 类型 - 减小字体
        JLabel typeLabel = createWrappedLabel("类型: " + book.type, new Font("微软雅黑", Font.PLAIN, 11));
        panel.add(typeLabel);

        return panel;
    }

    private JLabel createWrappedLabel(String text, Font font) {
        JLabel label = new JLabel("<html><div style='width:130px;text-align:left'>" + text + "</div></html>");
        label.setFont(font);
        label.setAlignmentX(Component.CENTER_ALIGNMENT);
        return label;
    }


    // 主方法用于测试
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new BookInfo());
    }
}
